package com.jiawang.core.handler;

import com.jiawang.core.annotations.component.JiaComponent;
import com.jiawang.core.constant.SingleDigitConstant;
import com.jiawang.core.constant.UriConstant;
import com.jiawang.core.enums.HandlerEnum;
import com.jiawang.core.log.LogUtils;
import com.jiawang.core.servlet.RequestBaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LiJiaWang
 * 创建时间: 23:17
 * 项目的名字: jio_writer_tomcat
 * <p style="color:#33CCFF">请求处理器</p>
 */
@JiaComponent
public class RequestHandler extends AbstractBaseHandler {
    private  LogUtils log =new LogUtils(RequestHandler.class.getCanonicalName());
    @Resource
    private RequestBaseServlet requestBaseServlet;

    /**
     * 连接通道
     */
    private Socket socket;


    public RequestHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void specific(HandlerEnum handlerEnum) {
        if (handlerEnum.equals(HandlerEnum.BASE)) {
            log.info("线程名称:" + Thread.currentThread().getName());

            try (
                    // 获取一个输入流的对象
                    BufferedReader inputStream = new BufferedReader(new InputStreamReader(this.getSocket().getInputStream()));
            ) {
                String requestContext = null;
                while ((requestContext = inputStream.readLine()) != null) {
                    System.out.println(requestContext);
                    if (UriConstant.ROW.equals(requestContext)) {
                        requestBaseServlet.getList().add(requestContext);
                    }
                }
                this.init(requestBaseServlet.getList());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {

            if (this.getHandler() != null) {
                this.getHandler().beginExecution();
            }
        }

    }

    /**
     * 初始化
     *
     * @param list 请求信息
     */
    public void init(List<String> list) {
        // 开始行,用来获取url请求方式和协议版本的字符串
        String firstLine = list.remove(SingleDigitConstant.ZERO);


        // 以空格分割
        String[] split = StringUtils.split(firstLine, UriConstant.PLACEHOLDER);

        // 获取方法
        requestBaseServlet.setRequestMethod(split[SingleDigitConstant.ZERO]);
        // 获取URI
        String uri = split[SingleDigitConstant.ONE];

        // 判断是否有问号,来决定是不是有请求参数
        if (StringUtils.contains(uri, UriConstant.QUESTION_MARK)) {

            // 找到第一个问号的位置
            int urlEndPosition = uri.indexOf(UriConstant.QUESTION_MARK);

            // 进行截取,得到url
            requestBaseServlet.setUrl(uri.substring(SingleDigitConstant.ZERO, urlEndPosition));

            //获取问号后面的字符,包含问号本身
            String paramString = uri.substring(urlEndPosition);

            // 判断这串字符是不是大于4,并且还有=符号
            if (paramString.length() > SingleDigitConstant.FOUR && StringUtils.contains(paramString, UriConstant.EQUAL_SIGN)) {

                //开始截取,从问号后面开始截取,得到参数字符串
                paramString = StringUtils.substring(paramString, SingleDigitConstant.ONE);

                //判断参数字符串是否是多个参数
                if (StringUtils.contains(paramString, UriConstant.AND_NUMBER)) {

                    //如果是多个参数那么就进行截取
                    String[] paramArrays = paramString.split(UriConstant.AND_NUMBER);

                    // 转换为Map
                    requestBaseServlet.setParams(Arrays.stream(paramArrays).map(item -> item.split(UriConstant.EQUAL_SIGN)).
                            collect(Collectors.toMap(paramArray -> paramArray[SingleDigitConstant.ZERO],
                                    paramArray -> paramArray[SingleDigitConstant.ONE])));
                } else {
                    // 如果没有多个参数,那么直接存储到Map
                    String[] param = paramString.split(UriConstant.EQUAL_SIGN);
                    requestBaseServlet.getParams().put(param[SingleDigitConstant.ZERO], param[SingleDigitConstant.ONE]);
                }
            }
        } else {
            // 如果没有参数,那么就直接是url
            requestBaseServlet.setUrl(uri);
        }
        // 获取协议版本
        requestBaseServlet.setVersion(split[SingleDigitConstant.TWO]);


        // 请求头信息赋值
        requestBaseServlet.setHeaderMap(list.stream().map(item -> item.split(UriConstant.COLON_SPACE)).
                collect(Collectors.toMap(headerArray -> headerArray[SingleDigitConstant.ZERO],
                        headerArray -> headerArray[SingleDigitConstant.ONE])));
    }

    public Socket getSocket() {
        return socket;
    }

    public RequestBaseServlet getRequestBaseServlet() {
        return requestBaseServlet;
    }
}
